package com.yang.utils;

import com.yang.pojo.Manager;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
@WebFilter("/*")
public class LoginFilter implements Filter {

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        //获取用户请求的资源的url（用户请求的资源可能是非受限资源，也可以是受限资源）
        String url = request.getRequestURL().toString();
        //从url中截取请求的资源名称（url字符串中最后一个/后面的部分）
        String path = url.substring(url.lastIndexOf("/") + 1);
        //如果url中截取的不是受限资源（不登陆也能访问的资源），则放行
        if("login.jsp".equals(path) || "LoginManagerServlet".equals(path) || "CheckCodeServlet".equals(path)
                || path.endsWith(".js") || path.endsWith(".css") || path.endsWith(".jpg") || path.endsWith(".bmp") || path.endsWith(".png") || path.endsWith("gif")){
            //非受限资源：登陆页面，登录页面的静态资源（js/css/image），验证码，servlet路径类
            filterChain.doFilter(servletRequest,servletResponse);
        }else {
            HttpSession session = request.getSession();
            Manager mgr = (Manager) session.getAttribute("mgr");
            if(mgr == null){
                //跳回登录页面
                request.setAttribute("tips","<label style='color:red'>请先登录!<label/>");
                request.getRequestDispatcher("login.jsp").forward(request,response);

            }else {
                //如果管理员登录则放行
                filterChain.doFilter(servletRequest,servletResponse);
            }
        }


    }
}
